<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, nextTick, PropType, ref, onMounted } from 'vue'
import useSchema from './hooks/useEntrySchema'
import { useCrudSchemas, AllSchemas, CrudSchema } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { CurdData } from '@/api/purchase/types'
import { Dialog } from '@/components/Dialog'
import { TableDialog } from '@/components/Custom/Purchase'
import { preViewDialogStore } from '@/store/modules/preViewDialog'
import { useI18n } from '@/hooks/web/useI18n'
import { getSupplierListApi } from '@/api/supplier'
import { getSelectListApi } from '@/api/operator'
import { FieldEnum } from '@/api/purchase/types'
import { getFieldEnumApi } from '@/api/purchase'
import { getListApi } from '@/api/product'
import { getCategoryListApi } from '@/api/category'
import { getBrandListApi } from '@/api/brand'
import { getSecondWarehouseListApi, getWarehouseListApi } from '@/api/warehouse/index'

defineOptions({
  name: 'PurchaseEntrySave'
})

const tableDialogStoreID = 'purchaseEntryWrite'
const itemTitleName = 'cname'
const tableDialogSelectedLimit = 50

const { t } = useI18n()

const categoryList = ref([])
const brandList = ref([])

const getCategoryList = async () => {
  const res = await getCategoryListApi({})
  if (res) {
    categoryList.value = res.data.list
  }
}

const getBrandList = async () => {
  const res = await getBrandListApi({})
  if (res) {
    brandList.value = res.data.list
  }
}

getCategoryList()
getBrandList()

const operatorList = ref([])

const getOperatorList = async () => {
  const res = await getSelectListApi({})
  if (res) {
    operatorList.value = res.data.list
  }
}
getOperatorList()

//获取仓库option
const warehouseList = ref([])

const getWarehouseList = async () => {
  const res = await getSecondWarehouseListApi({})
  if (res) {
    warehouseList.value = res.data.list
  }
}
getWarehouseList()

onMounted(async () => {})

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  },
  examine: {
    type: Boolean,
    default: () => false
  },
  futures: {
    type: Boolean,
    default: () => false
  }
})
const supplierList = ref([])

const getSupplierList = async () => {
  const res = await getSupplierListApi({})
  if (res) {
    supplierList.value = res.data.list
  }
}

getSupplierList()

const purchasePreViewId = 'purchasePreView'
const purchasePreViewIdStore = preViewDialogStore(purchasePreViewId)

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const rules: FormRules = reactive({})

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const purchaseFieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化

const tableDialogCurdSchema = reactive<CrudSchema[]>([
  {
    field: 'selection',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('product.id'),
    type: 'index',
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'cname',
    label: t('product.cname'),
    search: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'sku',
    label: t('product.sku'),
    form: {
      component: 'Input',
      formItemProps: {}
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'unit_value',
    label: t('product.unit'),
    form: {
      component: 'Input',
      formItemProps: {}
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'code',
    label: t('product.code'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'hashrate',
    label: t('product.hashrate'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'category',
    label: t('product.category'),
    search: {
      component: 'Select',
      componentProps: {
        options: categoryList
      }
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.category_value
        }
      }
    }
  },
  {
    field: 'brand',
    label: t('product.brand'),
    search: {
      component: 'Select',
      componentProps: {
        options: brandList
      }
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.brand_value
        }
      }
    }
  }
])
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    purchaseFieldEnum.value = res.data

    const { crudSchemas } = useSchema(
      undefined,
      supplierList,
      purchaseFieldEnum.value,
      tableDialogStoreID,
      tableDialogCurdSchema,
      operatorList,
      props.examine,
      warehouseList
    )
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      formSchema: newSchemas.formSchema || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    // formData.purchase_goods.forEach((item) => {
    //   if (item.unit_price == 0) {
    //     ElMessage.error('采购商品单价 不能为空!')
    //     return false
    //   }
    // })
    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    await nextTick()
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

const refresh = async () => {
  alert(123)
}

defineExpose({
  submit,
  refresh
})
</script>

<template>
  <Dialog
    v-model="purchasePreViewIdStore.isPreViewVisible"
    :title="t('imageViewerDemo.imageViewer')"
    width="50%"
  >
    <img class="w-full" :src="purchasePreViewIdStore.src" alt="Preview Image" />
  </Dialog>
  <!--  选择商品弹窗-->
  <TableDialog
    :getListApi="getListApi"
    :limit="tableDialogSelectedLimit"
    :tableDialogStoreID="tableDialogStoreID"
    :itemTitleName="itemTitleName"
  />
  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
